package com.lanou3g.zjl.chating.user.login;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.home.HomeActivity;
import com.lanou3g.zjl.chating.user.regist.RegisterActivity;
import com.lanou3g.zjl.chating.base.BaseActivity;
import com.lanou3g.zjl.chating.utils.ClearEditText;
import com.lanou3g.zjl.chating.utils.EaseCommonUtils;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by dllo on 15/11/17.
 * <p>
 * 测试
 */
public class LoginActivity extends BaseActivity {

    private boolean progressShow;    // 正在登录的提示框
    //    private boolean autoLogin = false;    // 是否登录成功过
    private boolean isSuccess = false;

    private String currentUsername;    // 用户输入的用户名
    private String currentPassword;    // 用户输入的密码
    private SharedPreferences sp; // 存储是否登录过
    private ProgressDialog pd;

    @Bind(R.id.loginName)
    ClearEditText loginName;

    @Bind(R.id.loginPsw)
    ClearEditText loginPsw;

    @Bind(R.id.loginBtn)
    Button loginBtn;

    @OnClick(R.id.loginBtn)
    void click() {
        login();
    }

    @OnClick(R.id.intoRegister_Tv)
    void intoRegister() {
        startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        sp = getSharedPreferences("zy", Context.MODE_PRIVATE);
        currentUsername = sp.getString("name", null);
        currentPassword = sp.getString("psw", null);

//        autoLogin = sp.getBoolean("isAutoLogin", false);
        // 如果登录成功过，直接进入主页面
        if (currentUsername != null && currentPassword != null) {
            loginName.setVisibility(View.GONE);
            loginPsw.setVisibility(View.GONE);
//            currentUsername = sp.getString("name", "");
//            currentPassword = sp.getString("psw", "");
//            connection();
            EMChatManager.getInstance().login(currentUsername, currentPassword, new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            EMGroupManager.getInstance().loadAllGroups();
                            EMChatManager.getInstance().loadAllConversations();
                            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                            intent.putExtra("username", currentUsername);
                            startActivity(intent);
                            finish();
                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
//                    Log.d("main", "登陆聊天服务器失败！");
                }
            });

        } else {
            loginName.setVisibility(View.VISIBLE);
            loginPsw.setVisibility(View.VISIBLE);
            // 如果用户名改变，清空密码
            loginName.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    loginPsw.setText(null);
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

        }
    }


    /**
     * 登录
     */
    public void login() {
        // 这句是连接服务器网络
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            /**
             * 网络不可用
             * */
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }
        currentUsername = loginName.getText().toString().trim();
        currentPassword = loginPsw.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            /**
             * 用户名不能为空
             * */
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(currentPassword)) {
            /**
             * 密码不能为空
             * */
            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        progressShow = true;
        pd = new ProgressDialog(LoginActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                progressShow = false;
            }
        });
        /**
         * 正在登录
         * */
        pd.setMessage(getString(R.string.Is_landing));
        pd.show();

        connection();
        return;
    }

    public void connection() {
        // 调用sdk登陆方法登陆聊天服务器
        EMChatManager.getInstance().login(currentUsername, currentPassword, new EMCallBack() {

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onSuccess() {
                pd.dismiss();
                isSuccess = true;
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                });
                EMGroupManager.getInstance().loadAllGroups();
                EMChatManager.getInstance().loadAllConversations();
                        onSuccesed(isSuccess);
            }

            @Override
            public void onError(final int code, final String message) {
                if (!progressShow) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    public void onSuccesed(boolean isSuccess) {
        this.isSuccess = isSuccess;

        SharedPreferences.Editor editor = sp.edit();
        // 登录成功过的状态
//        editor.putBoolean("isAutoLogin", true);
        editor.putString("name", currentUsername);
        editor.putString("psw", currentPassword);
        editor.commit();
        // ** 加载所有本地群和回话


        // 进入主页面
        if (isSuccess) {
            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
            intent.putExtra("username", currentUsername);
            startActivity(intent);
            finish();

        }
    }


}
